<?php
require_once(dirname(dirname(__FILE__)) . '/app.php');
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once dirname(__FILE__) ."/lib/WxPay.Api.php";
require_once dirname(__FILE__) .'/log.php';

//初始化日志
$logHandler= new CLogFileHandler(dirname(__FILE__) ."/logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);




$pin_order = DB::LimitQuery('pin_order', array(
	'condition' => array('state'=>0),
));
if($pin_order)
{
	
$access_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.WxPayConfig::APPID.'&secret='.WxPayConfig::APPSECRET;
$accss_token_arr = json_decode(file_get_contents($access_url));
$re_access_token = $accss_token_arr->access_token;

	foreach($pin_order as $pin_info)
	{
		$pin_order_list = DB::LimitQuery('pin_order_list', array(
			'condition' => array('pin_id'=>$pin_info['id']),
		));
		if($pin_order_list)
		{
			foreach($pin_order_list as $val)
			{
				//order_id
				$order = Table::Fetch('order', $val['order_id']);
				if($order['state'] == 'pay')
				{
					$team = Table::FetchForce('team', $order['team_id']);
					
					Table::UpdateCache('order', $val['order_id'], array(
							'service' => 'cash',
							'rstate' => 'berefund',
							'rereason'=>'开团失败',
							'state' => 'unpay'
					));
					
					$team = Table::Fetch('team', $order['team_id']);
					team_state($team);
					if ( $team['state'] != 'failure' ) {
						$minus = $team['conduser'] == 'Y' ? 1 : $order['quantity'];
						Table::UpdateCache('team', $team['id'], array(
									'now_number' => array( "now_number - {$minus}", ),
						));
					}
					Table::UpdateCache('order', $val['order_id'], array(
					'express_no' => '',
					));
					
					$user = Table::Fetch('user', $order['user_id'], 'id');
					$openId = $user['open_id'];
					//money
					$transaction_id = $order["trade_no"];
					$total_fee = $order["money"]*100;
					$refund_fee = $total_fee;
					$input = new WxPayRefund();
					$input->SetTransaction_id($transaction_id);
					$input->SetTotal_fee($total_fee);
					$input->SetRefund_fee($refund_fee);
					$refund_no = WxPayConfig::MCHID.date("YmdHis");
					
					$input->SetOut_refund_no($refund_no);
					$input->SetOp_user_id(WxPayConfig::MCHID);
					//var_dump(WxPayApi);die();
					printf_info(WxPayApi::refund($input));
					
					Log::DEBUG("退款日志:退款订单号:" . $val['order_id'].',退款金额： '.$order["money"].',退款给：openid='.$openId);
					$txt ='{
						"touser":"'.$openId.'",
						"msgtype":"text",
						"text":
							{
								 "content":"订单退款: 您的订单'.$val['order_id'].'参团未成功，现退款:'.$order['money'].'元，商品名称：'.$team['title'].'."
							}
						}';
					
					$url ='https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$re_access_token;
					$result = https_post($url,$txt);
				}
				//state
			}
			//state  = 2 update
			Table::UpdateCache('pin_order', $pin_info['id'], array(
					'state' => 2,
					));
		}
		
		
	}
		
}


var_dump($pin_order);
die();

function printf_info($data)
{
    foreach($data as $key=>$value){
        echo "<font color='#f00;'>$key</font> : $value <br/>";
    }
}

if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
	$transaction_id = $_REQUEST["transaction_id"];
	$total_fee = $_REQUEST["total_fee"];
	$refund_fee = $_REQUEST["refund_fee"];
	$input = new WxPayRefund();
	$input->SetTransaction_id($transaction_id);
	$input->SetTotal_fee($total_fee);
	$input->SetRefund_fee($refund_fee);
    $input->SetOut_refund_no(WxPayConfig::MCHID.date("YmdHis"));
    $input->SetOp_user_id(WxPayConfig::MCHID);
	printf_info(WxPayApi::refund($input));
	exit();
}

//$_REQUEST["out_trade_no"]= "122531270220150304194108";
///$_REQUEST["total_fee"]= "1";
//$_REQUEST["refund_fee"] = "1";
if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""){
	$out_trade_no = $_REQUEST["out_trade_no"];
	$total_fee = $_REQUEST["total_fee"];
	$refund_fee = $_REQUEST["refund_fee"];
	$input = new WxPayRefund();
	$input->SetOut_trade_no($out_trade_no);
	$input->SetTotal_fee($total_fee);
	$input->SetRefund_fee($refund_fee);
    $input->SetOut_refund_no(WxPayConfig::MCHID.date("YmdHis"));
    $input->SetOp_user_id(WxPayConfig::MCHID);
	printf_info(WxPayApi::refund($input));
	exit();
}
?>
<body>  
	<form action="#" method="post">
        <div style="margin-left:2%;color:#f00">微信订单号和商户订单号选少填一个，微信订单号优先：</div><br/>
        <div style="margin-left:2%;">微信订单号：</div><br/>
        <input type="text" style="width:96%;height:35px;margin-left:2%;" name="transaction_id" /><br /><br />
        <div style="margin-left:2%;">商户订单号：</div><br/>
        <input type="text" style="width:96%;height:35px;margin-left:2%;" name="out_trade_no" /><br /><br />
        <div style="margin-left:2%;">订单总金额(分)：</div><br/>
        <input type="text" style="width:96%;height:35px;margin-left:2%;" name="total_fee" /><br /><br />
        <div style="margin-left:2%;">退款金额(分)：</div><br/>
        <input type="text" style="width:96%;height:35px;margin-left:2%;" name="refund_fee" /><br /><br />
		<div align="center">
			<input type="submit" value="提交退款" style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer;  color:white;  font-size:16px;" type="button" onclick="callpay()" />
		</div>
	</form>
</body>
</html>